import axios, { AxiosError, AxiosRequestConfig } from "axios";

const devUrl = "http://localhost:8555";
const proUrl = "https://www.xiaohaoo.com/api/8555";

const BASE_URL: string = process.env.NODE_ENV === "development" ? devUrl : proUrl;

const axiosInstance = axios.create({
    baseURL: BASE_URL,
});

axiosInstance.interceptors.request.use(
    (config) => {
        return config;
    },
    (error: any) => Promise.reject(error)
);

axiosInstance.interceptors.response.use(
    (res) => res.data,
    (error: AxiosError) => {
        return Promise.reject(error);
    }
);
export const http = {
    get(url: string, params?: Record<string, any>, config?: AxiosRequestConfig) {
        return axiosInstance(
            config ?? {
                url,
                method: "GET",
                params,
            }
        ) as unknown as Promise<Record<string, any>>;
    },
    post(url: string, data?: Record<string, any>, config?: AxiosRequestConfig) {
        if (config) {
            config.data = config?.data ?? data;
            config.url = config?.url ?? url;
            config.method = "POST";
        }
        return axiosInstance(
            config ?? {
                url,
                method: "POST",
                data,
            }
        ) as unknown as Promise<Record<string, any>>;
    },

    delete(url: string, params?: Record<string, any>, config?: AxiosRequestConfig) {
        return axiosInstance(
            config ?? {
                url,
                method: "DELETE",
                params,
            }
        ) as unknown as Promise<Record<string, any>>;
    },
};
